<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/9/17
 * Time: 14:00
 */

namespace common\models\db;

use common\components\behaviors\UUIDBehavior;
use common\components\tools\Url;
use common\config\Env;
use common\members\wodrow\tools\Model;
use yii\base\Exception;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;

/**
 * Class Docu
 * @package common\models\db
 *
 * @property User $createdBy
 * @property User $updatedBy
 * @property DocuBody $docuBody
 * @property DocuTag[] $docuTags
 * @property Tag[] $tags
 *
 * @property-read string $url
 * @property-read string $listUrl
 * @property-read bool $isYours
 * @property-read bool $canOpt
 * @property bool $canLook
 */
class Docu extends \common\models\db\tables\Docu
{
    public $body = '';

    const TYPE_DEFAULT = 0;
    const TYPE_ARTICLE = 1;
    const TYPE_NEWS = 2;
    public static function getTypes()
    {
        return [
            self::TYPE_DEFAULT => "默认类型",
            self::TYPE_ARTICLE => "文章",
            self::TYPE_NEWS => "新闻",
        ];
    }
    const STATUS_DEFAULT = 0;
    const STATUS_DELETE = -10;
    public static function getStatus()
    {
        return [
            self::STATUS_DEFAULT => "默认状态",
            self::STATUS_DELETE => "已删除",
        ];
    }

    /**
     * @return string $url
     * @throws Exception
     */
    public function getUrl()
    {
        switch ($this->type){
            case self::TYPE_DEFAULT:
                $u_arr_0 = '/docu/default/view';
                break;
            case self::TYPE_NEWS:
                $u_arr_0 = '/docu/news/view';
                break;
            case self::TYPE_ARTICLE:
                $u_arr_0 = '/docu/article/view';
                break;
            default:
                throw new Exception("没有找到此类文档", 201810091050);
                break;
        }
        switch (\Yii::$app->appinfo->name){
            case Env::$yii2appid_home:
                return Url::to([$u_arr_0, 'uuid' => $this->uuid], true);
                break;
            default:
                return \common\config\Env::getUrls()['home_url']."{$u_arr_0}/".$this->uuid.\common\config\Env::$home_suffix;
                break;
        }
    }

    /**
     * @return string
     * @throws Exception
     */
    public function getListUrl()
    {
        switch ($this->type){
            case self::TYPE_DEFAULT:
                $u_arr_0 = '/docu/default/index';
                break;
            case self::TYPE_NEWS:
                $u_arr_0 = '/docu/news/index';
                break;
            case self::TYPE_ARTICLE:
                $u_arr_0 = '/docu/article/index';
                break;
            default:
                throw new Exception("没有找到此类文档", 201810091051);
                break;
        }
        switch (\Yii::$app->appinfo->name){
            case Env::$yii2appid_home:
                return Url::to([$u_arr_0], true);
                break;
            default:
                return \common\config\Env::getUrls()['home_url']."{$u_arr_0}".\common\config\Env::$home_suffix;
                break;
        }
    }

    /**
     * @return bool
     */
    public function getIsYours()
    {
        $bool = false;
        if (!\Yii::$app->user->isGuest){
            if ($this->created_by == \Yii::$app->user->identity->id){
                $bool = true;
            }
        }
        return $bool;
    }

    /**
     * @return bool
     */
    public function getCanOpt()
    {
        $bool = false;
        if (!\Yii::$app->user->isGuest){
            if ($this->isYours || \Yii::$app->user->identity->is_super){
                $bool = true;
            }
        }
        return $bool;
    }

    public function setCanLookCache($bool)
    {
        \Yii::$app->session->set('docu_canlook_', $bool, 3600);
    }

    /**
     * @return bool
     */
    public function getCanLook()
    {
        $bool = true;
//        \Yii::$app->session->delete('docu_canlook_');
        $cache = \Yii::$app->session->get('docu_canlook_');
        if ($this->look_pwd){
            $bool = false;
        }
        if ($this->isYours){
            $bool = true;
        }
        if ($cache){
            $bool = $cache;
        }
        return $bool;
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::class,
            ],
            'blameable' => [
                'class' => BlameableBehavior::class,
            ],
            'uuid' => [
                'class' => UUIDBehavior::class,
            ],
        ];
    }

    public function rules()
    {
        $a1 = parent::rules();
        foreach ($a1 as $k => $v){
            if ($v[1] == 'required'){
                if (is_array($v[0])){
                    $a1[$k][0] = array_diff($a1[$k][0], ['created_at', 'updated_at', 'created_by', 'updated_by', 'uuid']);
                }
            }
        }
        $rules = [
            [['look_pwd', 'pre_logo', 'desc'], 'default'],
            ['body', 'string'],
        ];
        $rules = ArrayHelper::merge($a1, $rules);
        return $rules;
    }

    public function attributeLabels()
    {
        $x = parent::attributeLabels();
        $y = [
            'pre_logo' => "预览图",
            'body' => "内容",
        ];
        $z = \common\components\tools\ArrayHelper::merge($x, $y);
        return $z;
    }

    public function afterFind()
    {
        parent::afterFind();
        if ($this->docuBody){
            $this->body = $this->docuBody->body;
        }
    }

    /**
     * @param bool $insert
     * @return bool
     * @throws \yii\db\Exception
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)){
            $docuBody = null;
            if ($this->body != ''){
                if ($this->docuBody){
                    if($this->body != $this->docuBody->body){
                        $docuBody = $this->docuBody;
                    }
                }else{
                    $docuBody = new DocuBody();
                    $docuBody->docu_id = $this->id;
                }
            }
            if ($docuBody){
                $docuBody->body = $this->body;
                if (!$docuBody->save()){
                    throw new \yii\db\Exception(Model::getModelError($docuBody), [], 201812130954);
                }
            }
            return true;
        }else{
            return false;
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'created_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUpdatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'updated_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDocuBody()
    {
        return $this->hasOne(DocuBody::className(), ['docu_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDocuTags()
    {
        return $this->hasMany(DocuTag::className(), ['docu_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('{{%docu_tag}}', ['docu_id' => 'id']);
    }
}